<template>
  <el-dialog
    :visible="show"
    :title="$t('email.addEmailAccount')"
    @open="open"
    @update:visible="$emit('update:show', false)"
    @closed="handleClosed"
  >
    <el-form
      ref="form"
      :model="emailForm"
      :rules="emailFormRules"
      label-width="170px"
    >
      <el-form-item label="发送显示名称">
        <el-input v-model="emailForm.name" />
      </el-form-item>
      <el-form-item :label="$t('email.emailType')" prop="emailType">
        <el-select
          v-model="emailForm.emailType"
          :placeholder="$t('email.emailType')"
          style="width: 100%"
          @change="handleEmailTypeChange"
        >
          <slot v-for="item in emailTypeOptions">
            <el-option :label="item.label" :value="item.value"></el-option>
          </slot>
        </el-select>
      </el-form-item>
      <!-- <el-form-item
        :label="$t('email.protocol')"
        prop="Driver"
        v-if="emailForm.emailType === '0'"
        :rules="driverRules.Driver"
      >
        <el-select
          v-model="emailForm.Driver"
          :placeholder="$t('common.select', [$t('email.protocol')])"
          style="width: 100%"
        >
          <slot v-for="item in emailServerTypeOptions">
            <el-option
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </slot>
        </el-select>
      </el-form-item> -->
      <el-form-item
        :label="$t('email.smtpServer')"
        prop="Host"
        :rules="hostRules.Host"
      >
        <el-input v-model="emailForm.Host"></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('email.port')"
        type="number"
        prop="Port"
        :rules="portRules.Port"
      >
        <el-input v-model="emailForm.Port"></el-input>
      </el-form-item>
      <el-form-item :label="$t('email.emailAddress')" prop="emailAddress">
        <el-input v-model="emailForm.emailAddress"></el-input>
      </el-form-item>
      <el-form-item :label="$t('email.apiKeyOrSecret')" prop="secret">
        <el-input v-model="emailForm.secret"></el-input>
      </el-form-item>
      <el-form-item label="开启ssl" prop="ssl" class="text-left">
        <el-switch v-model="emailForm.ssl"></el-switch>
      </el-form-item>
      <el-form-item
        label="每日最大发送数量"
        type="number"
        prop="maxLastDaySendNum"
        :rules="portRules.maxLastDaySendNum"
      >
        <el-input v-model="emailForm.maxLastDaySendNum"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForTesting('form')">{{
        $t('table.confirm')
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts">
import { validateEmail } from '@/utils/validate'
import { getAction, postAction } from '@/api/common'
export default {
  name: 'editAccount',
  props: {
    show: {
      required: true,
      type: Boolean,
    },
  },
  data() {
    return {
      emailForm: {
        Driver: 'SMTP',
        Host: null,
        Port: null,
        emailType: '0',
        emailAddress: '',
        secret: '',
        ssl: true,
        name: '',
        maxLastDaySendNum: 0,
      },
      emailTypeOptions: [
        { key: '0', label: this.$t('email.otherEmail'), value: '0' },
        { key: '1', label: this.$t('email.qqEmail'), value: '1' },
        { key: '2', label: this.$t('email.126Email'), value: '2' },
        { key: '3', label: this.$t('email.163email'), value: '3' },
        { key: '4', label: this.$t('email.sinaEmail'), value: '4' },
        { key: '5', label: this.$t('email.sohuEmail'), value: '5' },
        { key: '6', label: this.$t('email.googleEmail'), value: '6' },
        { key: '7', label: this.$t('email.outlookEmail'), value: '7' },
      ],
      emailServerTypeOptions: [
        { key: '0', label: 'SMTP', value: 'SMTP', disabled: false },
        { key: '1', label: 'IMAP', value: 'IMAP', disabled: true },
        { key: '2', label: 'POP3', value: 'POP3', disabled: true },
        { key: '3', label: 'Exchange', value: 'Exchange', disabled: true },
        { key: '4', label: 'CardDAV', value: 'CardDAV', disabled: true },
        { key: '5', label: 'CalDAV', value: 'CalDAV', disabled: true },
      ],
      driverRules: {
        Driver: [
          {
            required: true,
            message: this.$t('common.select', [this.$t('email.protocol')]),
            trigger: 'change',
          },
        ],
      },
      hostRules: {
        Host: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.smtpServer')]),
            trigger: 'blur',
          },
        ],
      },
      portRules: {
        Port: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.port')]),
            trigger: 'blur',
          },
        ],
        maxLastDaySendNum: [
          {
            required: true,
            message: this.$t('common.enter', ['每日最大发送数量']),
            trigger: 'blur',
          },
        ],
      },
      emailFormRules: {
        emailType: [
          {
            required: true,
            message: this.$t('common.select', [this.$t('email.emailType')]),
            trigger: 'change',
          },
        ],
        emailAddress: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.emailAddress')]),
            trigger: 'blur',
          },
          { validator: validateEmail, trigger: 'blur' },
          {
            min: 3,
            max: 320,
            message: this.$t('email.lengthFrom3To320'),
            trigger: 'blur',
          }, // 64 + @ + 255 //x@y
        ],
        secret: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.apiKeyOrSecret')]),
            trigger: 'blur',
          },
          {
            min: 6,
            max: 32,
            message: this.$t('email.lengthFrom6To32'),
            trigger: 'blur',
          },
        ],
      },
      infoLoading: false,
    }
  },
  methods: {
    async open() {},
    resetInfo() {
      this.$refs?.form.resetFields()
    },
    handleClosed() {
      this.$emit('update:show', false)
      this.resetInfo()
    },
    handleEmailTypeChange(val) {
      this.emailForm.Driver = 'SMTP'
      // this.emailForm.Port = 25
      this.emailForm.Port = 465
      this.emailForm.ssl = true
      if (val === '1') {
        this.emailForm.Host = 'smtp.qq.com'
      } else if (val === '2') {
        this.emailForm.Host = 'smtp.126.com'
      } else if (val === '3') {
        this.emailForm.Host = 'smtp.163.com'
      } else if (val === '4') {
        this.emailForm.Host = 'smtp.sina.com'
      } else if (val === '5') {
        this.emailForm.Host = 'smtp.sohu.com'
      } else if (val === '6') {
        this.emailForm.Host = 'smtp.gmail.com'
      } else if (val === '7') {
        // 勾选ssl验证时会报错，这里取消勾选
        this.emailForm.ssl = false
        this.emailForm.Port = 587
        this.emailForm.Host = 'smtp-mail.outlook.com'
      }
    },
    /// //////////////////////////发送账号//////////////////////////////////
    submitForTesting(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 验证的值没有过滤，需要过滤的话得加逻辑，问题不大，传到服务端并不作处理
          this.$common.ExeInvoke((f) => {
            let msg = f.VerifySmtp(
              this.emailForm.Host,
              parseInt(this.emailForm.Port),
              this.emailForm.ssl,
              this.emailForm.emailAddress,
              this.emailForm.secret
            )
            if (msg) {
              return this.$message.warning('邮箱授权未通过: ' + msg.Data)
            }
            this.emailForm.state = 1
            postAction(this.emailForm, 'EmailConfig/ConfigAddressee').then(
              (res) => {
                console.log(res)
                if (res.code === 20000) {
                  this.$message({
                    message: this.$t('email.emailAuthoritionSuccessfully'),
                    type: 'success',
                  })

                  this.$emit('update:show', false)
                  this.$emit('closeAction', this.emailForm.emailAddress)
                } else {
                  this.$message({
                    message:
                      res.message ?? this.$t('email.emailAuthoritionFailed'),
                    type: 'warning',
                  })
                }
                this.resetInfo()
              }
            )
          })
        } else {
          this.$message({
            message: this.$t('email.checkParams'),
            type: 'warning',
          })
          return false
        }
      })
    },
  },
}
</script>

<style scoped></style>
